// Copyright 2011 Google Inc. All Rights Reserved.

/**
 * @fileoverview View renderer for gcategorically.
 * @author vicfryzel@google.com (Vic Fryzel)
 */

/**
 * Initializes the top-level goog packages.
 */
var goog = goog || {};

/**
 * Initializes the goog.gcategorically package.
 */
goog.gcategorically = goog.gcategorically || {};

goog.gcategorically.COLLECTIONS_URI = "/collections.json";
goog.gcategorically.rootCollection = {};

/**
 * Onload handler to render the UI.
 */
goog.gcategorically.onload = function() {
  $(document).ready(function() {
    goog.gcategorically.refreshCollections();
  });
};

/**
 * Refresh the collections pane with the latest data.
 */
goog.gcategorically.refreshCollections = function() {
  $.get(goog.gcategorically.COLLECTIONS_URI, function(data) {
    goog.gcategorically.rootCollection = data;
    goog.gcategorically.renderCollectionTree(
        goog.gcategorically.getRootCollection(), 0);
  });
}

/**
 * Get the root collection set in goog.gcategorically.
 */
goog.gcategorically.getRootCollection = function() {
  return goog.gcategorically.rootCollection;
}

/**
 * Render the collection tree based on the given parameters.
 * 
 * Generate a series of elements into a buffer element, then replace the
 * contents of the buffer element into the target element on page for
 * display.  This makes rendering smoother on screen.
 */
goog.gcategorically.renderCollectionTree = function(
    collection, level, parent) {
  if (level == 0) {
    parent = $('#buffer .container');
  }
  
  // Generate the entire cell with its form and input elements.
  var cell = $('<div/>', {class: 'cell'}).appendTo(parent);
  var form = $('<form/>', {
      method: 'POST',
      action: goog.gcategorically.uploadUrl,
      enctype: 'multipart/form-data'}).appendTo(cell);
  $('<label/>', {text: collection.title}).appendTo(form);
  $('<input/>', {type: 'hidden', name: 'parent',
	  value: collection.resource_id}).appendTo(form);
  $('<input/>', {type: 'submit', name: 'submit', class: 'submit'})
      .appendTo(form);
  $('<input/>', {type: 'file', name: 'files[]', multiple: 'multiple',
	  class: 'file'})
	.appendTo(form)
    .bind('change', function(e) {
      $('.submit', $(this).parent()).click();
    });
  
  // Recursively add sub-cells to this cell.
  for (var i in collection.subCollections) {
    goog.gcategorically.renderCollectionTree(
        collection.subCollections[i], level + 1, cell);
  }
  
  if (level == 0) {
    // Move the buffer DOM to the primary container
    $('#collections .container').replaceWith($('#buffer .container'));
    $('<div/>', {class: 'container'}).appendTo($('#buffer'));

    var dragEnter = function (e) {
      if (!$(this).hasClass("hover")) {
      $(this).addClass("hover");
      }
    };
    var dragLeave = function (e) {
      $(this).removeClass("hover");
    };
    $('.cell').bind('dragover', dragEnter).bind('dragleave', dragLeave);
  }
  return cell;
}
